package com.rc.net;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.StrictMode;
import android.util.Log;

import com.rc.db.DatabaseSupport;
import com.rc.object.BaseObject;
import com.rc.util.Const;
import com.rc.util.MLog;
import com.telpoo.frame.utils.Cons.NetConfig;
import com.telpoo.frame.utils.FileSupport;
import com.telpoo.frame.utils.Mlog;

public class BaseNetSupport implements NetConfig {

	static String TAG = "NetSupport";

	public static String getData() {

		String result = "";

		return result;
	}

	@TargetApi(Build.VERSION_CODES.GINGERBREAD)
	@SuppressLint("NewApi")
	public static String method_POST(String url, String bodySend) {
		// "{\"type\":\"list\",\"from\":\"merchant_shop\",\"select\":\"shop_id,shop_name,m.email\",\"where\":{\"and\":{\"mt.status\":1}},\"limit\":2,\"offset\":1,\"order_by\":{\"mt.createdTime\":\"DESC\"},\"join\":[[\"sys_member as m\",\"m.memberId = mt.createdId\"]],\"sql\":1}";
		if (android.os.Build.VERSION.SDK_INT > 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}
		int retryCount = 0;

		do {
			try {

				URL myUrl = new URL(url);
				HttpClient client = newHttpClient();

				HttpConnectionParams.setConnectionTimeout(client.getParams(),
						CONNECTION_TIMEOUT);
				HttpResponse response;

				InputStream in = null;
				try {
					HttpPost post = new HttpPost(myUrl.toURI());
					StringEntity se = new StringEntity(bodySend, "UTF8");
					MLog.D("method_POST - url=" + myUrl);
					MLog.D("method_POST - json sent=" + bodySend);

					// BasicHeader basicHeader=new
					// BasicHeader(HTTP.CONTENT_TYPE, "application/json");

					MLog.D(readData(se.getContent()));

					se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
							"application/json"));
					se.setContentType(new BasicHeader("AUTH_TOKEN",
							Const.AUTHENKEY));

					se.setContentEncoding(HTTP.UTF_8);

					post.setEntity(se);
					response = client.execute(post);
					MLog.D("se.getContentType()" + se.getContentType());

					/* Checking response */
					if (response != null) {
						in = response.getEntity().getContent(); // Get the data
					}

				} catch (Exception e) {
					e.printStackTrace();
					MLog.E(TAG + "576237" + e.toString());
					return null;
				}
				String jsonContent = readData(in);
				MLog.D("method_POST - response: " + jsonContent);
				return jsonContent;
			} catch (FileNotFoundException ex) {
				Log.w("NAQ",
						"NetworkSupport - getNetworkData - FileNotFoundException = "
								+ ex.getMessage());
				return null;

			} catch (Exception ex) {
				Log.w("NAQ", "NetworkSupport - getNetworkData - Exception = "
						+ ex.getMessage());
				return null;
			}
		} while (++retryCount < NUMBER_OF_RETRY);

	}

	@TargetApi(Build.VERSION_CODES.GINGERBREAD)
	@SuppressLint("NewApi")
	public static String method_PUT(String url, String bodySend) {
		// "{\"type\":\"list\",\"from\":\"merchant_shop\",\"select\":\"shop_id,shop_name,m.email\",\"where\":{\"and\":{\"mt.status\":1}},\"limit\":2,\"offset\":1,\"order_by\":{\"mt.createdTime\":\"DESC\"},\"join\":[[\"sys_member as m\",\"m.memberId = mt.createdId\"]],\"sql\":1}";
		if (android.os.Build.VERSION.SDK_INT > 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}
		int retryCount = 0;

		do {
			try {

				URL myUrl = new URL(url);
				HttpClient client = newHttpClient();

				HttpConnectionParams.setConnectionTimeout(client.getParams(),
						CONNECTION_TIMEOUT);
				HttpResponse response;

				InputStream in = null;
				try {
					HttpPut put = new HttpPut(myUrl.toURI());
					StringEntity se = new StringEntity(bodySend, "UTF8");
					MLog.D("method_PUT - url=" + myUrl);
					MLog.D("method_PUT - json sent=" + bodySend);

					// BasicHeader basicHeader=new
					// BasicHeader(HTTP.CONTENT_TYPE, "application/json");

					MLog.D(readData(se.getContent()));

					se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
							"application/json"));
					se.setContentType(new BasicHeader("AUTH_TOKEN",
							Const.AUTHENKEY));

					se.setContentEncoding(HTTP.UTF_8);

					put.setEntity(se);
					response = client.execute(put);
					MLog.D("se.getContentType()" + se.getContentType());

					/* Checking response */
					if (response != null) {
						in = response.getEntity().getContent(); // Get the data
					}

				} catch (Exception e) {
					e.printStackTrace();
					MLog.E(TAG + "576237" + e.toString());
					return null;
				}
				String jsonContent = readData(in);
				MLog.D("method_POST - response: " + jsonContent);
				return jsonContent;
			} catch (FileNotFoundException ex) {
				Log.w("NAQ",
						"NetworkSupport - getNetworkData - FileNotFoundException = "
								+ ex.getMessage());
				return null;

			} catch (Exception ex) {
				Log.w("NAQ", "NetworkSupport - getNetworkData - Exception = "
						+ ex.getMessage());
				return null;
			}
		} while (++retryCount < NUMBER_OF_RETRY);

	}

	private static HttpClient newHttpClient() {
		HttpParams params = new BasicHttpParams();
		params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
				HttpVersion.HTTP_1_1);
		HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
		HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);
		HttpClient client = new DefaultHttpClient(params);
		return client;
	}

	private static String readData(InputStream in) throws IOException {
		if (in == null)
			return null;
		StringBuilder sb = new StringBuilder();
		BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000);
		for (String line = r.readLine(); line != null; line = r.readLine()) {
			sb.append(line);
		}
		in.close();
		return sb.toString();
	}

	public static ArrayList<BaseObject> parseJson(String TextJson, String[] keys) {
		ArrayList<BaseObject> arrBaseObject = new ArrayList<BaseObject>();
		String data = "";
		JSONObject jsonObj = null;
		JSONArray jsonArr = null;
		BaseObject baseObject;
		try {
			jsonObj = new JSONObject(TextJson);

			if ("success".equals(jsonObj.getString("status"))) {
				data = jsonObj.getString("data");
				jsonArr = new JSONArray(data);
				if (jsonArr != null) {
					for (int i = 0; i < jsonArr.length(); i++) {
						JSONObject oneObject = jsonArr.getJSONObject(i);
						baseObject = new BaseObject();
						for (String key : keys) {
							if (oneObject.has(key))
								baseObject.setParam(key,
										oneObject.getString(key));
							else
								MLog.w("ParseJson=0192321= no key:" + key);
						}
						arrBaseObject.add(baseObject);
					}
				}
			} else {
				data = jsonObj.getString("data");
				jsonObj = new JSONObject(data);
				baseObject = new BaseObject();
				if (jsonObj.has("message")) {
					baseObject
							.setParam("message", jsonObj.getString("message"));
					arrBaseObject.add(baseObject);
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			try {
				jsonObj = new JSONObject(data);
				baseObject = new BaseObject();
				for (String key : keys) {
					if (jsonObj.has(key))
						baseObject.setParam(key, jsonObj.getString(key));
					else
						MLog.w("ParseJson=0192321= no key:" + key);

				}
				arrBaseObject.add(baseObject);
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}

		return arrBaseObject;
	}

	public static ArrayList<BaseObject> parseJsonGetData(String TextJson,
			String[] keys, String parentKey) {
		if (TextJson == null) {
			return null;
		}
		ArrayList<BaseObject> arrBaseObject = new ArrayList<BaseObject>();
		String data = "";
		JSONObject jsonObj = null;
		JSONArray jsonArr = null;
		BaseObject baseObject = null;
		try {
			jsonObj = new JSONObject(TextJson);
			data = jsonObj.getString(parentKey);
			jsonArr = new JSONArray(data);
			if (jsonArr != null) {
				for (int i = 0; i < jsonArr.length(); i++) {
					JSONObject oneObject = jsonArr.getJSONObject(i);
					baseObject = new BaseObject();
					for (String key : keys) {
						if (oneObject.has(key))
							baseObject.setParam(key, oneObject.getString(key));
						else
							MLog.w("ParseJson=0192321= no key:" + key);
					}
					arrBaseObject.add(baseObject);
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			try {
				jsonObj = new JSONObject(data);
				jsonArr = new JSONArray();
				baseObject = new BaseObject();
				for (String key : keys) {
					if (jsonObj.has(key))
						baseObject.setParam(key, jsonObj.getString(key));
					else
						MLog.w("ParseJson=0192321= no key:" + key);

				}
				arrBaseObject.add(baseObject);

			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}

		return arrBaseObject;
	}

	public static String method_GET(String url, List<String> value) {

		int retryCount = 0;
		do {
			try {
				URL myUrl;
				if (value != null) {

					String query = "";
					for (String mstring : value) {
						query += mstring + "/";
					}
					myUrl = new URL(url + query);
				} else {
					myUrl = new URL(url);
				}
				Mlog.D(TAG + "- method_GET -URl:" + myUrl);

				HttpURLConnection conn = (HttpURLConnection) myUrl
						.openConnection();
				conn.setConnectTimeout(CONNECTION_TIMEOUT);
				conn.setReadTimeout(SO_TIMEOUT);
				if (Const.AUTHENKEY != null)
					conn.setRequestProperty("AUTH_TOKEN", Const.AUTHENKEY);
				MLog.D("AuthToken = " + Const.AUTHENKEY);

				conn.setRequestProperty("Content-Type", CONTENT_TYPE);

				String jsonContent = FileSupport.readFromInputStream(conn
						.getInputStream());
				Mlog.D(TAG + "- method_GET - json result=" + jsonContent);

				conn.disconnect();
				return jsonContent;
			} catch (FileNotFoundException ex) {
				Mlog.E(TAG
						+ "658345234 NetworkSupport - getNetworkData - FileNotFoundException = "
						+ ex.getMessage());

			} catch (Exception ex) {
				Mlog.E(TAG
						+ "789345564 NetworkSupport - getNetworkData - Exception = "
						+ ex.getMessage());
			}
		} while (++retryCount < NUMBER_OF_RETRY);

		return null;
	}

	@TargetApi(Build.VERSION_CODES.GINGERBREAD)
	@SuppressLint("NewApi")
	public static String method_Delete(String url, String bodySend) {
		// "{\"type\":\"list\",\"from\":\"merchant_shop\",\"select\":\"shop_id,shop_name,m.email\",\"where\":{\"and\":{\"mt.status\":1}},\"limit\":2,\"offset\":1,\"order_by\":{\"mt.createdTime\":\"DESC\"},\"join\":[[\"sys_member as m\",\"m.memberId = mt.createdId\"]],\"sql\":1}";
		if (android.os.Build.VERSION.SDK_INT > 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}
		int retryCount = 0;

		do {
			try {

				URL myUrl = new URL(url);
				HttpClient client = newHttpClient();

				HttpConnectionParams.setConnectionTimeout(client.getParams(),
						CONNECTION_TIMEOUT);
				HttpResponse response;

				InputStream in = null;
				try {
					HttpDeleteWithBody delete = new HttpDeleteWithBody(
							myUrl.toURI());
					StringEntity se = new StringEntity(bodySend, "UTF8");
					MLog.D("method_POST - url=" + myUrl);
					MLog.D("method_POST - json sent=" + bodySend);

					// BasicHeader basicHeader=new
					// BasicHeader(HTTP.CONTENT_TYPE, "application/json");

					MLog.D(readData(se.getContent()));

					se.setContentType(new BasicHeader("AUTH_TOKEN",
							Const.AUTHENKEY));

					se.setContentEncoding(HTTP.UTF_8);

					delete.setEntity(se);
					response = client.execute(delete);
					MLog.D("se.getContentType()" + se.getContentType());

					/* Checking response */
					if (response != null) {
						in = response.getEntity().getContent(); // Get the data
					}

				} catch (Exception e) {
					e.printStackTrace();
					MLog.E(TAG + "576237" + e.toString());
					return null;
				}
				String jsonContent = readData(in);
				MLog.D("method_POST - response: " + jsonContent);
				return jsonContent;
			} catch (FileNotFoundException ex) {
				Log.w("NAQ",
						"NetworkSupport - getNetworkData - FileNotFoundException = "
								+ ex.getMessage());
				return null;

			} catch (Exception ex) {
				Log.w("NAQ", "NetworkSupport - getNetworkData - Exception = "
						+ ex.getMessage());
				return null;
			}
		} while (++retryCount < NUMBER_OF_RETRY);

	}
}
